import * as TaskApi from '@/api/bpm/task'
import { getUser } from '@/api/system/user'
import * as NotifyTemplateApi from '@/api/system/notify/template'
import * as SmsTemplateApi from '@/api/system/sms/smsTemplate'
import { showToastAsync } from '@/utils/toast'
import * as MailTemplateApi from '@/api/system/mail/template'


interface ExpeditingOptions {
    processInstanceId?: string       // 流程实例ID
    userId?: number
    processName?: string            // 业务名称，用于模板参数
    templateCode?: string           // 可选：站内信模板编码，默认 expediting
    info?: Record<string, any>       // 额外信息对象
}


/**
* 流程催办通用函数
* 
*/
export const expediting = async (options: ExpeditingOptions) => {
    const { processInstanceId, userId, processName = '', templateCode,info } = options

    let currentApprover: any = null

    if (processInstanceId) {
        // 1️⃣ 查询任务列表
        const tasksList = await TaskApi.getTaskListByProcessInstanceId(processInstanceId)
        // 2️⃣ 只取 status === 1 且未完成的任务
        const pendingTasks = tasksList.filter((task: any) => task.status === 1 && task.status !== 4)
        if (!pendingTasks.length) return
        // 3️⃣ 获取当前审批人
        currentApprover = await getUser(pendingTasks[0].assigneeUser.id)
    } else {
        // 未传 processInstanceId，则必须传 userId，并直接查询该用户
        if (!userId) throw new Error('缺少 userId：未传 processInstanceId 时必须提供 userId')
        currentApprover = await getUser(userId)
    }

    if (!currentApprover) throw new Error('未找到目标用户')

    const finalTemplateCode = templateCode || 'expediting'


    // 4️⃣ 构造通知消息
    const messagePayload = {
        params: ['processName'],
        userId: currentApprover.id,
        userType: 2,
        templateCode: finalTemplateCode, // ✅ 使用传入的，否则默认 expediting
        templateParams:  { processName,...info } 
    }

    const smsPayload = {
        params: ['processName'],
        mobile: currentApprover.mobile,
        templateCode: finalTemplateCode,
        templateParams: { processName,...info } 
    }
    const emailPayload = {
        params: ['processName'],
        mail: currentApprover.email,
        templateCode: finalTemplateCode,
        templateParams: { processName,...info } 
    }

    // 5️⃣ 发送通知
    const logId1 = await NotifyTemplateApi.sendNotify(messagePayload as any)
    if (logId1) showToastAsync('通知消息发送成功！发送结果，见发送日志编号：' + logId1, 1500, 'none')

    //   const logId2 = await SmsTemplateApi.sendSms(smsPayload as any)
    //   if (logId2) showToastAsync('短信发送成功！发送结果，见发送日志编号：' + logId2)
    const logId3 = await MailTemplateApi.sendMail(emailPayload as any)
    if (logId3) showToastAsync('通知消息发送成功！发送结果，见发送日志编号：' + logId1, 1500, 'none')
}